package com.example.myapplication.ui.consumerInfo;
import android.app.Activity;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.Time;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;

import com.example.myapplication.App;
import com.example.myapplication.MainActivity;
import com.example.myapplication.R;
import com.example.myapplication.entity.Income;
import com.example.myapplication.entity.Pay;
import com.example.myapplication.greendao.DaoSession;
import com.example.myapplication.greendao.IncomeDao;
import com.example.myapplication.greendao.PayDao;
import com.example.myapplication.ui.income.IncomeFragment;
import com.tandong.bottomview.view.BottomView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.listener.ColumnChartOnValueSelectListener;
import lecho.lib.hellocharts.listener.PieChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;
import lecho.lib.hellocharts.view.PieChartView;


public class ConsumerFragment extends Fragment {

    private Button selecYear;
    private Button cancel_select_year;
    private TextView tv_consumer;
    private TextView tv_cs;
    private PieChartView piechart;
    private PieChartData data;         //存放数据
    private Integer currentYear;
    private Integer currentMonth;
    private String type = "year";
    private App app;
    private DaoSession daoSession;
    double life=0 ,travel=0,food=0,fun=0,learn=0,close = 0,sum = 0;
    String[] months = {"1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"};
    ArrayList<String> line_xlabel = new ArrayList<>();
    ArrayList<String> line_xlabel_year = new ArrayList<>();
    ArrayList<String> line_xlabel_month = new ArrayList<>();
    ArrayList<Double> score = new ArrayList<>();

    //折线图变量
    private Button test;
    private EditText edit;
    private LineChartView lineChart;

    private List<PointValue> mPointValues = new ArrayList<PointValue>();
    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_consumerinfo, null);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Time t=new Time();
        t.setToNow();
        currentYear = t.year;
        currentMonth = t.month+1;
        selecYear = getActivity().findViewById(R.id.select_year);
        selecYear.setText(currentYear+"年");

        piechart =  getActivity().findViewById(R.id.piechart);
        lineChart = getActivity().findViewById(R.id.line_chart);
        tv_consumer = getActivity().findViewById(R.id.tv_consumer);
        tv_cs = getActivity().findViewById(R.id.tv_cs);

        getDate(currentYear,currentMonth,type);

        initCharPie();
        initLineChart();
        setListeners();//按钮初始化
    }
    //创建饼状图
    private void initCharPie(){

        List<SliceValue> values = new ArrayList<SliceValue>();

        float ratio = (float)life;
        SliceValue sliceValue = new SliceValue(ratio, ChartUtils.pickColor());
        sliceValue.setLabel("生活日用"+":"+ratio);
        if (ratio>0.000001){
            values.add(sliceValue);
        }

        ratio =  (float)travel;
        sliceValue = new SliceValue(ratio, ChartUtils.pickColor());
        sliceValue.setLabel("交通出行"+":"+ratio);
        if (ratio>0.000001){
            values.add(sliceValue);
        }

        ratio = (float)food;
        sliceValue = new SliceValue(ratio, ChartUtils.pickColor());
        sliceValue.setLabel("餐饮美食"+":"+ratio);
        if (ratio>0.000001){
            values.add(sliceValue);
        }

        ratio = (float)fun;
        sliceValue = new SliceValue(ratio, ChartUtils.pickColor());
        sliceValue.setLabel("休闲娱乐"+":"+ratio);
        if (ratio>0.000001){
            values.add(sliceValue);
        }

        ratio = (float)learn;
        sliceValue = new SliceValue(ratio, ChartUtils.pickColor());
        sliceValue.setLabel("文体教育"+":"+ratio);
        if (ratio>0.000001){
            values.add(sliceValue);
        }

        ratio = (float)close;
        sliceValue = new SliceValue(ratio, ChartUtils.pickColor());
        sliceValue.setLabel("服饰美容"+":"+ratio);
        if (ratio>0.000001){
            values.add(sliceValue);
        }


        data = new PieChartData(values);

        data.setHasLabels(true);
        data.setHasLabelsOnlyForSelected(false);
        data.setHasLabelsOutside(false);
        data.setHasCenterCircle(true);

        data.setCenterText1("总支出"+sum);//设置中心文字1
        data.setCenterText1FontSize(20);    //字体大小

        piechart.setPieChartData(data);
    }

    //创建折线图
    private void initLineChart() {

        mAxisXValues.clear();
        mPointValues.clear();
        //获取x轴坐标
        for (int i = 0; i < line_xlabel.size(); i++) {
            mAxisXValues.add(new AxisValue(i).setLabel(line_xlabel.get(i)));
        }

        //获取坐标点数据
        for (int i = 0; i < score.size(); i++) {
            Float x = (float)score.get(i).doubleValue();
            mPointValues.add(new PointValue(i, x));
        }

        Line line = new Line(mPointValues).setColor(Color.parseColor("#FFCD41"));  //折线的颜色（橙色）
        List<Line> lines = new ArrayList<Line>();
        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line.setCubic(false);//曲线是否平滑，即是曲线还是折线
        line.setFilled(false);//是否填充曲线的面积
        line.setHasLabels(true);//曲线的数据坐标是否加上备注
//      line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
        line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示（每个数据点都是个大的圆点）
        lines.add(line);
        LineChartData data = new LineChartData();
        data.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(true);  //X坐标轴字体是斜的显示还是直的，true是斜的显示
        axisX.setTextColor(Color.GRAY);  //设置字体颜色

        axisX.setTextSize(10);//设置字体大小
        axisX.setMaxLabelChars(8); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
        //data.setAxisXTop(axisX);  //x 轴在顶部
        axisX.setHasLines(true); //x 轴分割线

        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        Axis axisY = new Axis();  //Y轴
        axisY.setName("");//y轴标注
        axisY.setInside(true);
        axisY.setTextColor(Color.parseColor("#000000"));
        axisX.setTextColor(Color.parseColor("#000000"));
        data.setAxisYLeft(axisY);  //Y轴设置在左边
        //data.setAxisYRight(axisY);  //y轴设置在右边


        //设置行为属性，支持缩放、滑动以及平移
        lineChart.setInteractive(true);
        lineChart.setZoomType(ZoomType.HORIZONTAL);
        lineChart.setMaxZoom((float) 2);//最大方法比例
        lineChart.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);
        lineChart.setLineChartData(data);
        lineChart.setVisibility(View.VISIBLE);
        /**注：下面的7，10只是代表一个数字去类比而已
         * 当时是为了解决X轴固定数据个数。见（http://forum.xda-developers.com/tools/programming/library-hellocharts-charting-library-t2904456/page2）;
         */
        Viewport v = new Viewport(lineChart.getMaximumViewport());
        v.left = 0;
        v.right = 7;
        lineChart.setCurrentViewport(v);
        /*
        这4句代码可以设置X轴数据的显示个数（x轴0-7个数据）。
        当数据点个数小于（29）的时候，缩小到极致hellochart默认的是所有显示。
        当数据点个数大于（29）的时候。
        若不设置axisX.setMaxLabelChars(int count)这句话,则会自动适配X轴所能显示的尽量合适的数据个数。
        若设置axisX.setMaxLabelChars(int count)这句话,33个数据点测试，
        若 axisX.setMaxLabelChars(10); 里面的10大于v.right= 7; 里面的7，则 刚开始X轴显示7条数据，
        然后缩放的时候X轴的个数会保证大于7小于10
        若小于v.right= 7;中的7,反正我感觉是这两句都好像失效了的样子 - -! 若这儿不设置 v.right= 7;
        这句话，则图表刚开始就会尽可能的显示所有数据，交互性太差
         */
    }
    private class Onclick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.select_year:
                    //Toast.makeText(getContext(), "插入成功123", Toast.LENGTH_SHORT).show();
                    BottomDialogFragment f = new BottomDialogFragment();
                    f.show(getChildFragmentManager(),"select_year");
                    break;
                default:
                    break;
            }
        }
    }

    private void setListeners() {
        Onclick onclick = new Onclick();
        selecYear.setOnClickListener(onclick);
    }
    @Subscribe
    public void onEvent(String data) {
        String[] s = data.split("!");
        type = s[2];
        currentYear = Integer.parseInt(s[0]);
        currentMonth = Integer.parseInt(s[1]);
        if (type.equals("month")){
            selecYear.setText(s[0]+"年"+s[1]+"月");
        }else {
            selecYear.setText(s[0]+"年");
        }
        getDate(currentYear,currentMonth,type);
        initCharPie();
        initLineChart();
    }

    public void getDate(int currentYear,int currentMonth,String type){
        //初始化数据
        life=0 ;
        travel=0;
        food=0;
        fun=0;
        learn=0;
        close = 0;
        sum = 0;
        score.clear();
        line_xlabel.clear();
        line_xlabel_month.clear();

        app = (App) getActivity().getApplication();
        daoSession = app.getDaoSession();
        PayDao dao = daoSession.getPayDao();
        List<Pay> daoList = dao.loadAll();

//        for (int i=0;i<10;i++){
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
//            Date date = new Date(System.currentTimeMillis());
//            Pay pay = new Pay();
//            pay.setPay(100.0);
//            pay.setPayDate(date);
//            pay.setPayType("learn");
//            dao.insert(pay);
//        }

        if (type.equals("month")){
            //按月计算
            int num = getDayNum(currentYear,currentMonth);

            for (int i=0;i<num;i++){
                score.add(0.0);
            }

            for (Pay pay: daoList){
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(pay.getPayDate());

                if (calendar.get(Calendar.YEAR)==currentYear && calendar.get(Calendar.MONTH)+1==currentMonth){

                    score.set(calendar.get(Calendar.DATE)-1,score.get(calendar.get(Calendar.DATE)-1)+pay.getPay());

                    if (pay.getPayType().equals("life")){
                        life+=pay.getPay();
                    }else if (pay.getPayType().equals("travel")){
                        travel+=pay.getPay();
                    }else if (pay.getPayType().equals("food")){
                        food+=pay.getPay();
                    }else if (pay.getPayType().equals("fun")){
                        fun+=pay.getPay();
                    }else if (pay.getPayType().equals("learn")){
                        learn+=pay.getPay();
                    }else if (pay.getPayType().equals("close")){
                        close+=pay.getPay();
                    }else {
                        continue;
                    }
                    sum+=pay.getPay();
                }
            }

            for (int i=0;i<num;i++){
                line_xlabel_month.add(""+currentMonth+"-"+(i+1));
            }
            line_xlabel = line_xlabel_month;

            tv_cs.setText("每日支出");

        }else {
            //按年计算
            for (int i=0;i<12;i++){
                score.add(0.0);
            }
            for (Pay pay: daoList){
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(pay.getPayDate());
                if (calendar.get(Calendar.YEAR)==currentYear){
                    System.out.println(pay.getPayDate());
                    System.out.println(Calendar.MONTH);
                    score.set(calendar.get(Calendar.MONTH),score.get(calendar.get(Calendar.MONTH))+pay.getPay());
                    //System.out.println(score);
                    if (pay.getPayType().equals("life")){
                        life+=pay.getPay();
                    }else if (pay.getPayType().equals("travel")){
                        travel+=pay.getPay();
                    }else if (pay.getPayType().equals("food")){
                        food+=pay.getPay();
                    }else if (pay.getPayType().equals("fun")){
                        fun+=pay.getPay();
                    }else if (pay.getPayType().equals("learn")){
                        learn+=pay.getPay();
                    }else if (pay.getPayType().equals("close")){
                        close+=pay.getPay();
                    }else {
                        continue;
                    }
                    sum+=pay.getPay();
                }
            }
            for (String s1:months){
                line_xlabel_year.add(s1);
            }
            line_xlabel = line_xlabel_year;
            tv_cs.setText("每月支出");
        }
        tv_consumer.setText("总支出:"+sum+"元");
    }
    public static int getDayNum(int year,int month) {
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                return 31;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            //对于2月份需要判断是否为闰年
            case 2:
                if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
                    return 29;
                } else {
                    return 28;
                }
            default:
                return 0;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}